package cn.com.thinker.security.sdk.shiro.filter;

import cn.com.thinker.security.sdk.shiro.dto.FilterDTO;
import cn.com.thinker.security.sdk.shiro.propertise.ShiroProperties;
import cn.com.thinker.security.sdk.shiro.token.SsoToken;
import cn.com.thinker.security.sdk.sso.handler.impl.DefaultClientLoginHandlerImpl;
import cn.com.thinker.security.sdk.sso.model.EncryCredentialInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by crazyHC on 2017/7/4.
 * 认证处理
 */
@Component("ssoLoginFilter")
@Slf4j
public class SsoLoginFilter extends AuthenticatingFilter {


    @Autowired
    private ShiroProperties properties;


    private String failureUrl ;


    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        EncryCredentialInfo encryCredentialInfo = (EncryCredentialInfo)httpRequest.getSession().getAttribute(DefaultClientLoginHandlerImpl.USER_KEY);
        encryCredentialInfo= encryCredentialInfo==null?new EncryCredentialInfo():encryCredentialInfo;
        return new SsoToken(encryCredentialInfo);
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return executeLogin(request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = getSubject(request, response);
        return subject.isAuthenticated();
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request,
                                     ServletResponse response) throws Exception {
//        issueSuccessRedirect(request, response);
        WebUtils.redirectToSavedRequest(request,response,getSuccessUrl());
        return false;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException ae, ServletRequest request,
                                     ServletResponse response) {
        if(failureUrl==null) {
            FilterDTO filter = properties.getFilter();
            failureUrl = filter == null ? "/error" : filter.getFailureUrl();
        }

        if (log.isDebugEnabled()) {
            log.debug( "Authentication exception", ae );
        }
        // is user authenticated or in remember me mode ?
        Subject subject = getSubject(request, response);
        if (subject.isAuthenticated() || subject.isRemembered()) {
            try {
                issueSuccessRedirect(request, response);
            } catch (Exception e) {
                log.error("Cannot redirect to the default success url", e);
            }
        } else {
            try {
                WebUtils.issueRedirect(request, response, failureUrl);
            } catch (IOException e) {
                log.error("Cannot redirect to failure url : {}", failureUrl, e);
            }
        }
        return false;
    }

    public void setFailureUrl(String failureUrl) {
        this.failureUrl = failureUrl;
    }

}
